package com.bml.architect.rabbitmq.confirm;

import com.bml.architect.rabbitmq.utils.RabbitConstant;
import com.bml.architect.rabbitmq.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息确认机制
 */
public class Weather {

    public static void main(String[] args) throws Exception {

        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        Map<String,String> param = new HashMap<>();
        param.put("sc.chengdu.20210201","四川成都20210201的天气多云");
        param.put("sc.deyang.20210201","四川德阳20210201的天气阴天");
        param.put("sc.yaan.20210201","四川雅安20210201的天气晴");
        param.put("sc.mianyang.20210201","四川绵阳20210201的天气小雨");

        param.put("heibei.sjz.20210202","河北石家庄20210202的天气多云");
        param.put("heibei.bd.20210202","河北保定20210202的天气阴天");
        param.put("hb.hs.20210202","河北衡水20210202的天气晴");
        param.put("hb.qhd.20210202","河北秦皇岛20210202的天气小雨");
        //开启confirm监听模式
        channel.confirmSelect();
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                //第二个参数代表接收的数据是否为批量接收，一般我们用不到。
                System.out.println("消息已被broker接受："+deliveryTag);
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("消息已被broker拒收:"+deliveryTag);
            }
        });

        channel.addReturnListener(new ReturnCallback() {
            @Override
            public void handle(Return returnMessage) {
                System.out.println("========================================================");
                System.err.println("return 交换机:"+returnMessage.getExchange());
                System.out.println("Return编码:"+returnMessage.getReplyCode() +",Return消息："+returnMessage.getReplyText());
                System.err.println("Return主题:"+new String(returnMessage.getBody()));
            }
        });

        for (Map.Entry<String,String> map : param.entrySet()){
            String key = map.getKey();
            String value = map.getValue();
            System.out.println(key);
            //Routing key 第二个参数相当于数据筛选的条件
            //第三个参数为：mandatory true代表如果消息无法正常投递则return回生产者，如果false，则直接将消息放弃。
            channel.basicPublish(RabbitConstant.exchange_weather_topic,key,true,null,value.getBytes());
        }



    }
}
